package com.example.mypc.myapplication;

import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private VideoView vv;
    private LinearLayout ll_container;
    private ImageView pause;
    private ImageView next_left;
    private ImageView next_right;
    //是否有下一个视频
    private boolean hasRight=false;
    //是否有上一个视频
    private boolean hasLeft=false;
    //是否播放
    private boolean isStart=true;
    //视频播放的个数
    private int count=0;
    private List<Uri> mList;

    public static final int MEDIA_PLAY_TIME = 0X23;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MEDIA_PLAY_TIME:
                    int n=  msg.arg1;
                    Log.i("TAG",">>>>>>>>>>>>>>>"+n);
                    upDateProgress(n);
                    if (vv.isPlaying()) {
                        MyProgressBar pb = (MyProgressBar) ll_container.getChildAt(n);
                        pb.setProgress(vv.getCurrentPosition());
                        handler.sendEmptyMessageDelayed(MEDIA_PLAY_TIME, 500);
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ProgressBar progressBar=new ProgressBar(this);
        progressBar.setMax(100);
        initView();
        mList = initData();
        assert mList !=null;
        //设置进度条最大进度
        initProgress(0);
        //对ViedeoView的一些设置
        vv.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer player, int i, int i1) {
                return true;
            }
        });
        vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer player) {
                if(count<2&&count>-1){
                    count++;
                    initProgress(count);
                    upDateProgress(count);
                }else {
                    Toast.makeText(MainActivity.this,"锻炼完成",Toast.LENGTH_SHORT).show();
                    count=0;
                }
            }
        });
    }

    //更新进度
    private void upDateProgress(int i){
        MediaMetadataRetriever mmr=new MediaMetadataRetriever();
       for(int n=0;n<i;n++){
           MyProgressBar at = (MyProgressBar) ll_container.getChildAt(n);
           mmr.setDataSource(this,mList.get(n));
           // 播放时长单位为毫秒
           String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
           at.setProgress(Integer.parseInt(duration));
       }
//        MyProgressBar at = (MyProgressBar) ll_container.getChildAt(i);
//        at.setProgress(vv.getCurrentPosition());
    }

    //设置最大进度及播放源
    private void initProgress(final int i){
        //设置播放的视频
        vv.setVideoURI(mList.get(i));
        //videoview.getDuration()方法必须在监听中才有效
        vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer player) {
                vv.start();
                int duration = vv.getDuration();
                MyProgressBar pb = (MyProgressBar)ll_container.getChildAt(i);
                pb.setMax(duration);
                Message obtain = Message.obtain();
                obtain.arg1=i;
                obtain.what=MEDIA_PLAY_TIME;
                handler.sendMessage(obtain);
            }
        });

    }

    //初始化播放源及进度条
    private List<Uri> initData(){
        Uri parse1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_1);
        Uri parse2 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_2);
        Uri parse3 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_3);
        Uri parse4 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_1);
        Uri parse5 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_2);
        Uri parse6 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_3);
        Uri parse7 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_1);
        Uri parse8 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_2);
        Uri parse9 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.guide_3);
        List<Uri> list=new ArrayList<>();
        list.add(parse1);
        list.add(parse2);
        list.add(parse3);
        list.add(parse4);
        list.add(parse5);
        list.add(parse6);
        list.add(parse7);
        list.add(parse8);
        list.add(parse9);
        //视频的各个长度
        List<Integer> durations=new ArrayList<>();
        //视频总长度
        InputStream stream1 = getResources().openRawResource(R.raw.guide_1);
        InputStream stream2 = getResources().openRawResource(R.raw.guide_2);
        InputStream stream3 = getResources().openRawResource(R.raw.guide_3);
        //各自视频长度(超级坑，数据类型超过了int类型)
        try {
            int i1 = stream1.available();
            int i2 = stream2.available();
            int i3 = stream3.available();
            durations.add(i1);
            durations.add(i2);
            durations.add(i3);
            for(int i=0;i<list.size();i++){
                MyProgressBar pb=new MyProgressBar(this);
//                pb.setIndeterminate(false);
                //set padding
                pb.setPadding(0);
                //set bacground color
                pb.setBgColor(Color.BLACK);
                //set progress color
                pb.setProgressColor(Color.GREEN);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( 0, ViewGroup.LayoutParams.MATCH_PARENT,durations.get(i)/1000);
                if(i>0){
                    params.setMargins(5,0,0,0);
                }
                pb.setLayoutParams(params);
                ll_container.addView(pb);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void initView() {
        vv = (VideoView) findViewById(R.id.vv);
        ll_container = (LinearLayout) findViewById(R.id.ll_container);
        pause = (ImageView) findViewById(R.id.pause);
        pause.setOnClickListener(this);
        next_left = (ImageView) findViewById(R.id.next_left);
        next_left.setOnClickListener(this);
        next_right = (ImageView) findViewById(R.id.next_right);
        next_right.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()){
            //暂停
            case R.id.pause:
                if(vv.isPlaying()){
                    vv.pause();
                }else {
                    vv.start();
                    Message obtain = Message.obtain();
                    obtain.arg1=count;
                    obtain.what=MEDIA_PLAY_TIME;
                    handler.sendMessage(obtain);
                }
                isStart=!isStart;
                break;
            //上一个视频
            case R.id.next_left:
                count--;
                if(count<0){
                    Toast.makeText(MainActivity.this,"已经是第一条视频",Toast.LENGTH_SHORT).show();
                    count=0;
                    return;
                }
                initProgress(count);
                upDateProgress(count);
                break;
            //下一个视频
            case R.id.next_right:
                count++;
                if(count>2){
                    Toast.makeText(MainActivity.this,"已经是最后一条视频",Toast.LENGTH_SHORT).show();
                    count=2;
                    return;
                }
                initProgress(count);
                upDateProgress(count);
                break;
        }
    }
}
